import { fetchDcsInfo } from '@/api/manager/dcs'
import { transDcsModel } from '@/api/manager/dcs/translator'
import { fetchInteractiveList } from '@/api/manager/interactive'
import { transInteractive } from '@/api/manager/interactive/translator'
import { fetchLiveInfo } from '@/api/manager/live'
import { transLive } from '@/api/manager/live/translator'
import { Meeting } from '@/api/manager/meeting'
import { Mt, MtEntity } from '@/api/manager/mt'
import { fetchOftenList } from '@/api/manager/often'
import { transOften } from '@/api/manager/often/translator'
import { transVipList } from '@/api/manager/vip/translator'
import { uniqBy } from 'lodash-es'
import { useManagerStore } from './blocks/main/manager/store'
import { useParamsStore } from './blocks/main/store'
import { useTableAllStore } from './blocks/main/table/all/store'
import { MccModel, mccCascadeVOs, transCascade, transMtEntityList } from './blocks/main/table/all/translator'
import { getItemByMtKey, getItemInTree, meetingListSort, mtListSort } from './blocks/main/table/all/utils'
import { useTableDcsStore } from './blocks/main/table/dcs/store'
import { dcsListSort } from './blocks/main/table/dcs/utils'
import { useTableInteractiveStore } from './blocks/main/table/interactive/store'
import { mtListInteractiveSort } from './blocks/main/table/interactive/utils'
import { useTableLiveStore } from './blocks/main/table/live/store'
import { liveListSort } from './blocks/main/table/live/utils'
import { useTableOftenStore } from './blocks/main/table/often/store'
import { oftenMtSort } from './blocks/main/table/often/utils'
import { useTableOrgStore } from './blocks/main/table/organize/store'
import { useVipStore } from './blocks/vip/store'
import { transEntityMtToMeeting } from './utils/translator'
import { useMccStore } from './store'
import { isMatch } from './utils/utils'
import { fetchAllMts, fetchCascadeNodes } from '@/api/manager/main'
interface IMeetingInfoInit {
	mccCascadeVOs: mccCascadeVOs
	vipList: MtEntity[]
	speaker: MtEntity
	chairman: MtEntity
	chairman_selectview: 0 | 1
}
// 会议信息 ，全部终端信息初始化 ， 发言方管理方初始化 获取
export const fetchGetMeetingInfoInit = async (params: IMeetingInfoInit) => {
	const { mccCascadeVOs, vipList, speaker, chairman, chairman_selectview } = params
	const dcsList = useTableDcsStore.getState().list
	//vip
	const vip = transVipList(vipList)
	useVipStore.setState({
		list: vip,
	})
	//tableAll
	const keywords = useParamsStore.getState().keywords
	const sortType = useParamsStore.getState().tableSort
	let [meetingList, curLevelMtList] = transCascade(mccCascadeVOs)
	const vipSortMtKeys = vipList.map((x) => x.mt_key)
	const dcsMtKeys = dcsList.filter((x) => x.dcs.isDcs).map((x) => x.mtKey)
	for (const cascade of meetingList) {
		let children = meetingList.filter((x) => x.mcc.parentId === cascade.mcc.id)
		children = meetingListSort(children, sortType).map((x) => {
			x.status.isOpen = false
			if (!x.mcc.status.isOnline) {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
			}
			return x
		})
		cascade.children = children
	}
	let curMeeting = meetingList.find((x) => x.mtKey === '0.0.0.0_0')
	if (curMeeting) {
		curLevelMtList = mtListSort(curLevelMtList, sortType, vipSortMtKeys).map((x) => {
			x.status.isMatchSearch = isMatch(x.mcc, keywords)
			x.mcc.status.isDcs = dcsMtKeys.includes(x.mtKey)
			return x
		})
		curMeeting.children = [...curLevelMtList, ...curMeeting.children]
		curMeeting.status.isOpen = true //默认展开
		curMeeting.mcc.status.isOnline = true //后台没给当前会议的状态，得手动设值
	}
	let root = meetingList.find((x) => x.mcc.parentId === '0')
	if (root) {
		root.status.isOpen = true
	}
	useTableAllStore.setState({
		tree: root ?? meetingList[0],
	})
	//speaker chairman
	let s, c
	if (speaker) {
		if (speaker.mt_type !== 7 && speaker.mt_type !== 8) {
			s = {
				speaker: new Mt(speaker),
			}
		} else {
			let parentId = ''
			let cascade = mccCascadeVOs.find((x) => x.mt_key === speaker.mt_key)
			if (cascade) {
				parentId = cascade.parent_id
			}
			let currentMeeting = mccCascadeVOs.find((x) => x.mt_key === '0.0.0.0_0')
			if (currentMeeting) {
				let mt = currentMeeting.mts.find((x) => x.mt_key === speaker.mt_key)
				if (mt) {
					parentId = currentMeeting.id
				}
			}
			//下下级离线的会议，初始化不会给，所以 parentId 只能为空
			let meeting = transEntityMtToMeeting(speaker, parentId)
			s = {
				speaker: new Meeting(meeting),
			}
		}
	}
	if (chairman) {
		c = {
			chairman: new Mt(chairman),
		}
	}
	useManagerStore.setState({ ...s, ...c, isChairmanSelectView: chairman_selectview === 1 })
	//dcs 设置发言管理状态
	for (const item of dcsList) {
		if (chairman && chairman.mt_key === item.mtKey) {
			item.mcc.status.isChairman = true
		} else {
			item.mcc.status.isChairman = false
		}
		if (speaker && speaker.mt_key === item.mtKey) {
			item.mcc.status.isSpeaker = true
		} else {
			item.mcc.status.isSpeaker = false
		}
	}
	useTableDcsStore.setState({
		list: [...dcsList],
	})
}
export const fetchOftenInit = async () => {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	const mts = await fetchOftenList(meetingMoid)
	if (mts) {
		const keywords = useParamsStore.getState().keywords
		const vipList = useVipStore.getState().list
		let list = mts
			.map((x) => transOften(x))
			.map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
		const vipMtKeyList = vipList.map((x) => x.mtKey)
		let result = oftenMtSort(list, vipMtKeyList)
		useTableOftenStore.setState({
			list: result,
		})
	}
}
export const fetchInteractiveInit = async () => {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	const mts = await fetchInteractiveList(meetingMoid)
	if (mts) {
		const keywords = useParamsStore.getState().keywords
		const sortType = useParamsStore.getState().tableSort
		const vipList = useVipStore.getState().list
		let list = mts
			.map((x) => transInteractive(x))
			.map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
		const vipMtKeyList = vipList.map((x) => x.mtKey)
		let result = mtListInteractiveSort(list, sortType, vipMtKeyList)
		useTableInteractiveStore.setState({
			list: result,
		})
	}
}
export const fetchDcsInit = async () => {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	const res = await fetchDcsInfo(meetingMoid)
	if (res) {
		const { mts = [], dcsMode } = res
		const chairman = useManagerStore.getState().chairman
		const speaker = useManagerStore.getState().speaker
		const keywords = useParamsStore.getState().keywords
		let list = mts
			.map((x) => transDcsModel(x))
			.filter((x) => x.mcc.status.isOnline || x.dcs.isDcs)
			.map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
		list = dcsListSort(list)
		for (const item of list) {
			if (chairman && chairman.mtKey === item.mtKey) {
				item.mcc.status.isChairman = true
			} else {
				item.mcc.status.isChairman = false
			}
			if (speaker && speaker.mtKey === item.mtKey) {
				item.mcc.status.isSpeaker = true
			} else {
				item.mcc.status.isSpeaker = false
			}
		}
		useTableDcsStore.setState({
			isDcs: dcsMode !== 0,
			dcsMode,
			list,
		})
		//处理回写到 tableAll
		const tree = useTableAllStore.getState().tree
		const dcsMtKeys = list.filter((x) => x.dcs.isDcs).map((x) => x.mtKey)
		getItemInTree(tree, (item) => {
			if (item.mcc.isMt) {
				if (dcsMtKeys.includes(item.mtKey)) {
					item.mcc.status.isDcs = true
				} else {
					item.mcc.status.isDcs = false
				}
			}
		})
		useTableAllStore.setState({
			tree: { ...tree },
		})
		//处理回写到 tableOften
		const oftenList = useTableOftenStore.getState().list
		for (const item of oftenList) {
			if (dcsMtKeys.includes(item.mtKey)) {
				item.mcc.status.isDcs = true
			} else {
				item.mcc.status.isDcs = false
			}
		}
		useTableOftenStore.setState({
			list: [...oftenList],
		})
		//处理回写到 tableOrg
		const orgList = useTableOrgStore.getState().list
		for (const item of orgList) {
			if (dcsMtKeys.includes(item.mtKey)) {
				item.mcc.status.isDcs = true
			} else {
				item.mcc.status.isDcs = false
			}
		}
		useTableOrgStore.setState({
			list: [...orgList],
		})
	}
}
export const fetchLiveInit = async () => {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	const res = await fetchLiveInfo(meetingMoid)
	if (res) {
		const { mts = [], live } = res
		const keywords = useParamsStore.getState().keywords
		let list = mts
			.map((x) => transLive(x))
			.map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				return x
			})
		list = liveListSort(list)
		useTableLiveStore.setState({ list, isLive: !!live })
	}
}
export const toggleTableAll = async (prevMeetingModel: Omit<MccModel<Meeting>, 'attr' | 'children'>) => {
	const {
		status,
		mcc: { id },
		mtKey,
	} = prevMeetingModel
	prevMeetingModel.status.isOpen = !prevMeetingModel.status.isOpen
	if (status.isOpen && mtKey !== '0.0.0.0_0') {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const list = await fetchCascadeNodes({ meetingMoid, id })
		//请求回来后，状态变更已经不展开了，就直接不继续更新tree
		if (!status.isOpen || !list) return
		const tree = useTableAllStore.getState().tree
		const dcsList = useTableDcsStore.getState().list
		const keywords = useParamsStore.getState().keywords
		const sortType = useParamsStore.getState().tableSort
		let meetingModel = getItemByMtKey(tree, mtKey)
		if (meetingModel) {
			//展开获取的数据 = 离线会议 + 终端
			let [addMeetingList, addMtList] = transMtEntityList(list, id)
			const meetingList = meetingModel.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
			const dcsMtKeys = dcsList.filter((x) => x.dcs.isDcs).map((x) => x.mtKey)
			const resultMtList = mtListSort(addMtList, sortType, []).map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				x.mcc.status.isDcs = dcsMtKeys.includes(x.mtKey)
				return x
			})
			const resultMeetingList = meetingListSort(
				uniqBy([...addMeetingList, ...meetingList], (val) => val.mtKey),
				sortType
			).map((x) => {
				x.status.isOpen = false
				if (!x.mcc.status.isOnline) {
					x.status.isMatchSearch = isMatch(x.mcc, keywords)
				}
				return x
			})
			meetingModel.children = [...resultMtList, ...resultMeetingList]
		}
		useTableAllStore.setState({
			tree: { ...tree },
		})
	} else {
		const tree = useTableAllStore.getState().tree
		useTableAllStore.setState({
			tree: { ...tree },
		})
	}
}
/**获取所有终端包括下级的 */
export const fetchAllMtsInit = async () => {
	const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
	let mts = await fetchAllMts(meetingMoid)
	if (mts) {
		//过滤掉在线的级联会议和离线会议的下级终端，走外头的缓存，仅保留离线下级会议。因为不会有本级会议，而且结构都是终端形式结构。
		let _list = mts.filter((x) => x.mt_type !== 8).filter((x) => !!x.mt_id)
		//处理回写到 tableAll
		const tree = useTableAllStore.getState().tree
		const dcsList = useTableDcsStore.getState().list
		const dcsMtKeys = dcsList.filter((x) => x.dcs.isDcs).map((x) => x.mtKey)
		const keywords = useParamsStore.getState().keywords
		const sortType = useParamsStore.getState().tableSort
		const vipList = useVipStore.getState().list
		const vipSortMtKeys = vipList.map((x) => x.mtKey)
		getItemInTree(tree, (parent) => {
			if (!parent.mcc.isMt) {
				let list = _list.filter((x) => x.conf_e164 === parent.mcc.account)
				let [addMeetingList, addMtList] = transMtEntityList(list, parent.mcc.id)
				const meetingList = parent.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
				const resultMtList = mtListSort(
					addMtList,
					sortType,
					parent.mtKey === '0.0.0.0_0' ? vipSortMtKeys : []
				).map((x) => {
					x.status.isMatchSearch = isMatch(x.mcc, keywords)
					x.mcc.status.isDcs = dcsMtKeys.includes(x.mtKey)
					return x
				})
				const resultMeetingList = meetingListSort(
					uniqBy([...addMeetingList, ...meetingList], (val) => val.mtKey),
					sortType
				).map((x) => {
					if (!x.mcc.status.isOnline) {
						x.status.isMatchSearch = isMatch(x.mcc, keywords)
					}
					return x
				})
				parent.children = [...resultMtList, ...resultMeetingList]
			}
		})
		useTableAllStore.setState({
			tree: { ...tree },
		})
	}
}
/**仅处理展开的请求进行更新缓存，给新画面合成等功能内部展示需要 */
export const fetchToggleTree = async (model: { status: { isOpen: boolean }; mcc: { id: string }; mtKey: string }) => {
	const {
		status,
		mcc: { id },
		mtKey,
	} = model
	if (status.isOpen && mtKey !== '0.0.0.0_0') {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const list = await fetchCascadeNodes({ meetingMoid, id })
		if (!list) return
		const tree = useTableAllStore.getState().tree
		const dcsList = useTableDcsStore.getState().list
		const keywords = useParamsStore.getState().keywords
		const sortType = useParamsStore.getState().tableSort
		let meetingModel = getItemByMtKey(tree, mtKey)
		if (meetingModel) {
			//展开获取的数据 = 离线会议 + 终端
			let [addMeetingList, addMtList] = transMtEntityList(list, id)
			const meetingList = meetingModel.children.filter((x) => !x.mcc.isMt) as MccModel<Meeting>[]
			const dcsMtKeys = dcsList.filter((x) => x.dcs.isDcs).map((x) => x.mtKey)
			const resultMtList = mtListSort(addMtList, sortType, []).map((x) => {
				x.status.isMatchSearch = isMatch(x.mcc, keywords)
				x.mcc.status.isDcs = dcsMtKeys.includes(x.mtKey)
				return x
			})
			const resultMeetingList = meetingListSort(
				uniqBy([...addMeetingList, ...meetingList], (val) => val.mtKey),
				sortType
			).map((x) => {
				if (!x.mcc.status.isOnline) {
					x.status.isMatchSearch = isMatch(x.mcc, keywords)
				}
				return x
			})
			meetingModel.children = [...resultMtList, ...resultMeetingList]
		}
		useTableAllStore.setState({
			tree: { ...tree },
		})
	} else {
		const tree = useTableAllStore.getState().tree
		useTableAllStore.setState({
			tree: { ...tree },
		})
	}
}
